<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/16
 * Time: 13:20
 */

namespace App\HttpController\Home;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class Battle extends Base
{
    public function lol_Discard()//废弃
    {
        $battle = [];
        $battle_id = $this->request()->getQueryParam('battle_id');
        if( !$battle_id ){
            return $this->writeJson(0,null,'缺少battle_id参数');
        }
        $url = UrlEnums::FJURL.UrlEnums::LOL_LIVE_BATTLE_PATH."?battle_id={$battle_id}&version=2";
        $client = new HttpClient($url);
        list($s1, $s2) = explode(' ', microtime());
        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
        $option = [
            'path'      => UrlEnums::LOL_LIVE_BATTLE_PATH,
            'api_time'  => $microtime
        ];
        $header = Auth::getInstance()->header($option);
        $client->setHeaders($header,true,false);
        $response = $client->get();
        $content = $response->getBody();
        $data = json_decode($content,true);
        if( isset($data['code']) && $data['code'] == 200 ){
            $battle = $data['data'];
            $data['code'] = 1;
        }
        return $this->writeJson($data['code'],$battle,$data['message']);
    }

    /**
     * lol战役详情
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function lol()
    {
        $battle_id = $this->request()->getQueryParam('battle_id');
        $match_id = $this->request()->getQueryParam('match_id');
        if( empty($battle_id) || !$battle_id ){
            return $this->writeJson(0,null,'缺少battle_id参数');
        }
        if( empty($match_id) || !$match_id ){
            return $this->writeJson(0,null,'缺少match_id参数');
        }
        $match = MysqlPool::invoke(function (MysqlObject $db)use($match_id){
            return $db->where('match_id',$match_id)->getOne('siam_lolmatchs');
        });
        if( !$match ){
            return $this->writeJson(0,null,'没有该场比赛！');
        }

        if( $match['status'] == 1 ){
            $url = UrlEnums::FJURL.UrlEnums::LOL_LIVE_BATTLE_PATH."?battle_id={$battle_id}&version=2";
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => UrlEnums::LOL_LIVE_BATTLE_PATH,
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $content = $response->getBody();
            $data = json_decode($content,true);
            if( isset($data['code']) && $data['code'] == 200 ){
                foreach ( $data['data']['team_stats'] as $k=>$v ){
                    $team = MysqlPool::invoke(function (MysqlObject $db)use($v){
                        return $db->where('team_id',$v['team_id'])->getOne('siam_lolteams','name,name_en,short_name,logo');
                    });
                    $data['data']['team_stats'][$k]['team'] = $team;
                }
                return $this->writeJson(1,$data['data'],'请求成功');
            }else{
                return $this->writeJson(0,null,$data['message']);
            }
        }else{
            $battle = MysqlPool::invoke(function (MysqlObject $db)use($battle_id){
                $battle = $db->where('battle_id',$battle_id)->getOne('siam_lollive_battle');
                if( !$battle ){
                    return $battle;
                }
                $battle['player_stats'] = json_decode($battle['player_stats'],true);
                $battle['economic_diff'] = json_decode($battle['economic_diff'],true);
                $battle['xp_diff'] = json_decode($battle['xp_diff'],true);
                $battle['duration'] = floor($battle['duration']/60).'′'.$battle['duration']%60;
                foreach ($battle['player_stats'] as $k=>$player_stat){
                    $equip_ids = $player_stat['equip_ids'];//装备IDs
                    $battle['player_stats'][$k]['equips'] = $db->whereIn('item_id',$equip_ids)->get('siam_lolitems');
                }
                $battle['team_stats'] = json_decode($battle['team_stats'],true);
                foreach ( $battle['team_stats'] as $k=>$v ){
                    $team = MysqlPool::invoke(function (MysqlObject $db)use($v){
                        return $db->where('team_id',$v['team_id'])->getOne('siam_lolteams','name,name_en,short_name,logo');
                    });
                    $battle['team_stats'][$k]['team'] = $team;
                }
                return $battle;
            });
            return $this->writeJson(1,$battle,'请求成功');
        }


    }

    /**
     * dota战役详情
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function dota()
    {
        $battle_id = $this->request()->getQueryParam('battle_id');
        $match_id = $this->request()->getQueryParam('match_id');
        if( empty($battle_id) || !$battle_id ){
            return $this->writeJson(0,null,'缺少battle_id参数');
        }
        if( empty($match_id) || !$match_id ){
            return $this->writeJson(0,null,'缺少match_id参数');
        }
        $match = MysqlPool::invoke(function (MysqlObject $db)use($match_id){
            return $db->where('match_id',$match_id)->getOne('siam_dotamatchs');
        });
        if( !$match ){
            return $this->writeJson(0,null,'没有该场比赛！');
        }
        if( $match['status'] == 1 ){
            $url = UrlEnums::FJURL.UrlEnums::DOTA_LIVE_BATTLE_PATH."?battle_id={$battle_id}&version=2";
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => UrlEnums::DOTA_LIVE_BATTLE_PATH,
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $content = $response->getBody();
            $data = json_decode($content,true);
            if( isset($data['code']) && $data['code'] == 200 ){
                $battle = $data['data'];
                $battle['player_stats'] = $battle['players'];
                return $this->writeJson(1,$battle,'请求成功');
            }else{
                return $this->writeJson(0,null,$data['message']);
            }
        }else{
            $battle = MysqlPool::invoke(function (MysqlObject $db)use($battle_id){
                $battle = $db->where('battle_id',$battle_id)->getOne('siam_dotalive_battle');
                if( !$battle ){
                    return $battle;
                }
                $battle['player_stats'] = json_decode($battle['player_stats'],true);
                $battle['economic_diff'] = json_decode($battle['economic_diff'],true);
                $battle['xp_diff'] = json_decode($battle['xp_diff'],true);
                $battle['team_stats'] = json_decode($battle['team_stats'],true);
                $battle['duration'] = floor($battle['duration']/60).'′'.$battle['duration']%60;
                return $battle;
            });
            return $this->writeJson(1,$battle,'请求成功');
        }


    }

    /**
     * csgo战役
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function csgo()
    {
        $map_name = $this->request()->getQueryParam('map_name');
        $match_id = $this->request()->getQueryParam('match_id');
        if( !$map_name ){ //地图
            return $this->writeJson(0,null,'缺少map_name参数');
        }
        if( !$match_id ){ //比赛ID
            return $this->writeJson(0,null,'缺少match_id参数');
        }
        //比赛详情
        $match = MysqlPool::invoke(function (MysqlObject $db)use($match_id){
            return $db->where('match_id',$match_id)->getOne("siam_csgomatchs");
        });
        if( !$match ){
            return $this->writeJson(0,null,'改场比赛不存在');
        }
        if( $match['status'] == 1 ){
            $url = UrlEnums::FJURL.UrlEnums::CSGO_LIVE_BATTLE_PATH."?match_id={$match_id}&map_name={$map_name}&version=2";
            $client = new HttpClient($url);
            list($s1, $s2) = explode(' ', microtime());
            $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
            $option = [
                'path'      => UrlEnums::CSGO_LIVE_BATTLE_PATH,
                'api_time'  => $microtime
            ];
            $header = Auth::getInstance()->header($option);
            $client->setHeaders($header,true,false);
            $response = $client->get();
            $content = $response->getBody();
            $data = json_decode($content,true);
            if( isset($data['code']) && $data['code'] == 200 ){
                $battle = $data['data'];
                $res = [];
                $res['map_name'] = $map_name;
                $res['team_a_id'] = $battle['counter_terrorist_team_id'];
                $res['team_a_name'] = $battle['counter_terrorist_team_name'];
                $res['team_a_score'] = $battle['counter_terrorist_team_score'];
                $res['team_a']['player'] = $battle['counter_terrorist_players'];
                //上半场胜利记录
                $res['team_a']['round_history_first_half'] = $battle['counter_terrorist_round_history_first_half'];
                //下半场胜利记录
                $res['team_a']['round_history_second_half'] = $battle['counter_terrorist_round_history_second_half'];

                $res['team_b_id'] = $battle['terrorist_team_id'];
                $res['team_b_name'] = $battle['terrorist_team_name'];
                $res['team_b_score'] = $battle['terrorist_team_score'];
                $res['team_b']['player'] = $battle['terrorist_players'];
                $res['team_b']['round_history_first_half'] = $battle['terrorist_round_history_first_half'];
                $res['team_b']['round_history_second_half'] = $battle['terrorist_round_history_second_half'];

                return $this->writeJson(1,$res,'请求成功');
            }else{
                return $this->writeJson(0,null,$data['message']);
            }
        }else{
            //team_a:警，team_b:匪
            $data = MysqlPool::invoke(function (MysqlObject $db)use($map_name,$match_id){
                $battle = $db->where('map_name',$map_name)->where('match_id',$match_id)->getOne('siam_csgolive_battle');
                $data = [];
                if( !$battle ){
                    return $data;
                }
                $data['map_name'] = $map_name;
                $data['team_a_id'] = $battle['counter_terrorist_team_id'];
                $data['team_a_name'] = $battle['counter_terrorist_team_name'];
                $data['team_a_score'] = $battle['counter_terrorist_team_score'];
                $data['team_a']['player'] = json_decode($battle['counter_terrorist_players'],true);
                //上半场胜利记录
                $data['team_a']['round_history_first_half'] = json_decode($battle['counter_terrorist_round_history_first_half'],true);
                //下半场胜利记录
                $data['team_a']['round_history_second_half'] = json_decode($battle['counter_terrorist_round_history_second_half'],true);

                $data['team_b_id'] = $battle['terrorist_team_id'];
                $data['team_b_name'] = $battle['terrorist_team_name'];
                $data['team_b_score'] = $battle['terrorist_team_score'];
                $data['team_b']['player'] = json_decode($battle['terrorist_players'],true);
                $data['team_b']['round_history_first_half'] = json_decode($battle['terrorist_round_history_first_half'],true);
                $data['team_b']['round_history_second_half'] = json_decode($battle['terrorist_round_history_second_half']);
                return $data;
            });
            return $this->writeJson(1,$data,'请求成功');
        }

    }

    /**
     * kog战役详情
     * @return bool
     * @throws \EasySwoole\Component\Pool\Exception\PoolEmpty
     * @throws \EasySwoole\Component\Pool\Exception\PoolException
     * @throws \Throwable
     */
    public function kog()
    {
        $battle_id = $this->request()->getQueryParam('battle_id');
        $match_id = $this->request()->getQueryParam('match_id');
        if( empty($battle_id) || !$battle_id ){
            return $this->writeJson(0,null,'缺少battle_id参数');
        }
        if( empty($match_id) || !$match_id ){
            return $this->writeJson(0,null,'缺少match_id参数');
        }
        $match = MysqlPool::invoke(function (MysqlObject $db)use($match_id){
            return $db->where('match_id',$match_id)->getOne('siam_kogmatchs');
        });
        if( !$match ){
            return $this->writeJson(0,null,'没有该场比赛！');
        }
        $battle = MysqlPool::invoke(function (MysqlObject $db)use($battle_id){
            $battle = $db->where('battle_id',$battle_id)->getOne('siam_koglive_battle');
            if( !$battle ){
                return $battle;
            }
            $battle['player_stats'] = json_decode($battle['player_stats'],true);
            $battle['status'] = 2;
            foreach ( $battle['player_stats'] as $k1=>$v2 ){
                $hero = $db->where('hero_id',$v2['hero_id'])->getOne('siam_kogheroes');
                $battle['player_stats'][$k1]['hero_name'] = $hero['name'];
                $battle['player_stats'][$k1]['hero_avatar'] = $hero['avatar'];
                $player = $db->where('player_id',$v2['player_id'])->getOne('siam_kogplayer','player_id,nickname,avatar');
                $battle['player_stats'][$k1]['player_avatar'] = $player['avatar'];
                $battle['player_stats'][$k1]['player_name'] = $player['nickname'];
            }
            $battle['duration'] = floor($battle['duration']/60).'′'.$battle['duration']%60;
            foreach ($battle['player_stats'] as $k=>$player_stat){
                $equip_ids = $player_stat['equip_ids'];//装备IDs
                $battle['player_stats'][$k]['equips'] = $db->whereIn('item_id',$equip_ids)->get('siam_kogitems');
            }
            $battle['team_stats'] = json_decode($battle['team_stats'],true);
            foreach ( $battle['team_stats'] as $k=>$v ){
                $team = MysqlPool::invoke(function (MysqlObject $db)use($v){
                    return $db->where('team_id',$v['team_id'])->getOne('siam_kogteams','name,name_en,short_name,logo');
                });
                $battle['team_stats'][$k]['team'] = $team;
            }
            return $battle;
        });
        return $this->writeJson(1,$battle,'请求成功');
    }

    public function csgodetail_Discard() //废弃
    {
        $map_name = $this->request()->getQueryParam('map_name');
        $match_id = $this->request()->getQueryParam('match_id');
        MysqlPool::invoke(function (MysqlObject $db)use($map_name,$match_id){
            $battle = $db->where('map_name',$map_name)->where('match_id',$match_id)->getOne('siam_csgolive_battle');
            $ct_history_first_half = json_decode($battle['counter_terrorist_round_history_first_half'],true);
            $ct_history_second_half = json_decode($battle['counter_terrorist_round_history_second_half'],true);
            $ct_history = array_merge_recursive($ct_history_first_half,$ct_history_second_half);
            if( count($ct_history) >=16 ){

            }
        });
    }
}